package com.example.springboot_system.serviceImpl;


import com.example.springboot_system.mapper.*;
import com.example.springboot_system.pojo.*;
import com.example.springboot_system.pojo.vo.register.*;
import com.example.springboot_system.service.RegisterService;
import com.example.springboot_system.utils.DateUtil;
import com.example.springboot_system.utils.IdCardValidUtil;
import com.example.springboot_system.utils.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//import static com.xgs.hisystem.util.card.Card.defaultGetCardId;

/**
 *
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private OutpatientQueueMapper outpatientQueueMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public ResponseResult addPatientInfor(Patient patient) {

        boolean bool = IdCardValidUtil.validateIdCard(patient.getIdCard());
        if (!bool) {
            return new ResponseResult(201, "身份证号码非法！");
        }
        //验证该就诊卡是否已被使用
        Patient patient1 = patientMapper.findByCardId(patient.getCardId());
        if (!StringUtils.isEmpty(patient1)) {
            return new ResponseResult(202, "ACTIVATED");
        }
        //验证患者已注册过就诊卡
        Patient patient2 = patientMapper.findByIdCard(patient.getIdCard());
        if (!StringUtils.isEmpty(patient2)) {
            return new ResponseResult(203, "COVER");
        }
        String id = (int) ((Math.random() * 9 + 1) * 100000) + "";
        patient.setId(id);
        patientMapper.save(patient);
        return new ResponseResult(200, "新办就诊卡成功");
    }

    @Override
    public ResponseResult getCardIdInfor(GetCardIdInforReqVO reqVO) throws Exception {
        PatientInforRspVO rspVO = new PatientInforRspVO();

        try {
            System.out.println("卡号：" + reqVO.getCardId());
            //获取患者信息
            Patient patient = patientMapper.findByCardId(reqVO.getCardId());
            System.out.println("获取患者信息：" + patient);

            String patientId = patient.getId();
            List<Register> registerList = registerMapper.findByPatientId(patientId);

            if (registerList != null && !registerList.isEmpty()) {
                for (Register register : registerList) {
                    int registerStatus = register.getRegisterStatus();
                    System.out.println("已挂号状态registerStatus：" + registerStatus);
                    int treatmentStatus = register.getTreatmentStatus();
                    System.out.println("就诊状态treatmentStatus:" + treatmentStatus);
                    int chargeStatus = register.getChargeStatus();
                    System.out.println("缴费状态charge Status：" + chargeStatus);
                    //已就诊未缴费
                    if (chargeStatus == 0) {
                        rspVO.setMessage("存在已挂号未就诊的记录，请及时缴费！");
                        return new ResponseResult(202, "存在已就诊未收费的记录，请及时缴费！", rspVO);
                    }

                    //已挂号
                    if (registerStatus == 1) {
                        //未就诊情况下
                        if (treatmentStatus == 0) {
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                            String creDate = df.format(register.getCreateDatetime());
                            System.out.println("数据库创建日期："+ creDate);
                            String nowDate = DateUtil.getCurrentDateSimpleToString();
                            System.out.println("当前日期："+nowDate);
                            //当天情况下
                            if (nowDate.equals(creDate)) {
                                //检查门诊队列是否待处理状态，1是，0否
                                OutpatientQueue outpatientQueue = outpatientQueueMapper.findByRegisterId(register.getId());
                                if (outpatientQueue != null && outpatientQueue.getOutpatientQueueStatus() == 1) {
                                    String doctorName = Arrays.asList(outpatientQueue.getDescription().split("#")).get(1);
                                    rspVO.setMessage("当日有未完成的就诊，请完成就诊！门诊医生：" + doctorName);
                                    return new ResponseResult(201, "当日有未完成的就诊，请完成就诊！门诊医生：", rspVO);
                                }
                            }
                            //不是当天则修改挂号状态为：-1 （过期）
                            else {
                                register.setRegisterStatus(-1);
                                registerMapper.updateRegisterStatus(register.getRegisterStatus(), register.getId());
                            }
                        }

                    }
                }
            }

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String birthdayString = sdf.format(patient.getBirthday());
            rspVO.setAge(DateUtil.getAge(birthdayString));
            BeanUtils.copyProperties(patient, rspVO);
        } catch (Exception e) {
            e.printStackTrace();
            rspVO.setMessage("查询就诊卡信息失败，请检查添加就诊卡时输入信息是否规范！");
            return new ResponseResult(203, "查询就诊卡信息失败，请检查添加就诊卡时输入信息是否规范！", rspVO);
        }
        return new ResponseResult(200, rspVO);
    }

    /**
     * 挂号获取医生
     *
     * @param reqVO
     * @return
     */
    @Override
    public List<RegisterDoctorRspVO> getAllRegisterDoctor(RegisterTypeReqVO reqVO) {

        List<RegisterDoctorRspVO> registerDoctorRspList = new ArrayList<>();

        List<User> userList = userMapper.findByDepartmentAndDepartmentType(reqVO.getDepartment(), reqVO.getRegisterType());

        if (userList != null && userList.size() > 0) {
            userList.forEach(user -> {
//                //更新已挂号数
//                if (!DateUtil.getCurrentDateSimpleToString().equals(user.getUpdateTime())) {
//                    user.setNowNum(0);
//                    user.setUpdateTime(new Date());
////                    iUserRepository.saveAndFlush(user);
//                    userMapper.update(user);
//                }
                RegisterDoctorRspVO registerDoctorRspVO = new RegisterDoctorRspVO();
                registerDoctorRspVO.setDoctorName(user.getUsername());
                registerDoctorRspVO.setAllowNum(user.getAllowNum());
                registerDoctorRspVO.setNowNum(user.getNowNum());
                registerDoctorRspVO.setWorkDateTime(user.getWorkDateTime());
                registerDoctorRspVO.setPrice(user.getTreatmentPrice());
                registerDoctorRspVO.setId(user.getId());
                registerDoctorRspVO.setWorkAddress(user.getWorkAddress());

                registerDoctorRspList.add(registerDoctorRspVO);
            });
        }
        return registerDoctorRspList;
    }

    @Override
    public List<RegisterRecordRspVO> getRegisterRecord(RegisterRecordSearchReqVO reqVO) {
//        System.out.println("动态查询reqVO的时间：");
//        System.out.println("startTime:" + reqVO.getStartTime());
//        System.out.println("endTime:" + reqVO.getEndTime());
        List<Register> registerList = registerMapper.findAllWithCondition(reqVO);
//        for (Register r : registerList) {
//            System.out.println("registerList中元素：" + r);
//        }
        List<RegisterRecordRspVO> recordRspVOList = new ArrayList<>();

        for (int i = 0; i < registerList.size(); i++) {
            Register register = registerList.get(i);
            RegisterRecordRspVO recordRspVO = new RegisterRecordRspVO();
            String patientId = register.getPatientId();
            Patient patient = patientMapper.findById(patientId);
            recordRspVO.setCardId(patient.getCardId());
            String departmentName = null;
            Department department = departmentMapper.findByCode(Integer.parseInt(register.getDepartment()));
            if (department != null) {
                departmentName = department.getName();
            }
            recordRspVO.setDepartment(departmentName);
            recordRspVO.setName(patient.getName());
            recordRspVO.setDoctor(register.getDoctor());
            recordRspVO.setRegisterType(register.getRegisterType());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String createTime = sdf.format(register.getCreateDatetime());
            recordRspVO.setCreateDateTime(createTime);
            recordRspVO.setCreatePerson(register.getOperatorName());
            recordRspVO.setCreatePersonEmail(register.getOperatorEmail());

//            System.out.println("单个实体recoreRspVO：" + recordRspVO);
            recordRspVOList.add(recordRspVO);
        }
//        System.out.println("集合recordRspVOList:" + recordRspVOList);
        return recordRspVOList;
    }


    @Override
    public ResponseResult addRegisterInfor(RegisterInforReqVO reqVO, HttpSession session) {
        try {
//            String userId = (String) session.getAttribute("id");
//            User user = userMapper.findById(userId);
            User user = (User) session.getAttribute("user");
            /*User user = userMapper.findById(user1.getId());*/
            if (user==null) {
                return new ResponseResult(205, "当前会话已过期，请重新登录！");
            }
            User userDoctor = userMapper.findById(reqVO.getDoctorId());
            if (userDoctor == null) {
                return new ResponseResult(201, "未查询到相关医生信息，请稍后重试！");
            }
            Integer allowNum = userDoctor.getAllowNum();
            Integer nowNum = userDoctor.getNowNum();
            if (allowNum == nowNum) {
                return new ResponseResult(202, "该医生已挂号人数已达上限，请刷新页面重新选择！");
            }
            Patient patient = patientMapper.findByCardId(reqVO.getCardId());
            //患者当前门诊队列状态是待处理，验证第二次挂的是否为体检号
            // 当天
            String nowDate = DateUtil.getCurrentDateSimpleToString();
            String dayStart = nowDate.concat(" 00:00:00");
            String dayEnd = nowDate.concat(" 23:59:59");
            List<Register> registerList = registerMapper.findAllByPidAndStatus(patient.getId(), dayStart, dayEnd);
            if (registerList != null && !registerList.isEmpty()) {
                if (registerList.size() != 1) {
                    return new ResponseResult(203, "挂号记录异常，请联系管理员！");
                }
                if (!"12".equals(reqVO.getDepartment())) {
                    return new ResponseResult(204, "门诊待处理状态，只允许再挂体检号！");
                }
            }
            //更新已挂号数量
            userDoctor.setNowNum(nowNum + 1);
            userMapper.update(userDoctor);
            //保存挂号记录
            Register register = new Register();
            //生成一个随机的id
            String id = (int) ((Math.random() * 9 + 1) * 100000) + "";
            register.setId(id);
            register.setDepartment(reqVO.getDepartment());
            register.setDoctor(reqVO.getDoctor());
            register.setDoctorId(reqVO.getDoctorId());
            register.setOperatorName(user.getUsername());
            register.setOperatorEmail(user.getEmail());
            register.setPatientId(patient.getId());
            register.setPayType(reqVO.getPayType());
            register.setRegisterType(reqVO.getRegisterType());
            register.setTreatmentPrice(reqVO.getTreatmentPrice());
            register.setRegisterStatus(1);

            String registeredNum = "RE" + System.currentTimeMillis() + (int) (Math.random() * 900 + 100);
            register.setRegisteredNum(registeredNum);

            registerMapper.save(register);

           /* //将患者加入门诊队列
            OutpatientQueue outpatientQueue = new OutpatientQueue();
            //生成一个随机的id
            String opid = (int) ((Math.random() * 9 + 1) * 100000) + "";
            outpatientQueue.setId(opid);
            outpatientQueue.setPatientId(patient.getId());
            outpatientQueue.setRegisterId(register.getId());
            outpatientQueue.setUserId(userDoctor.getId());
            outpatientQueue.setDescription(patient.getName() + '#' + userDoctor.getUsername());
            outpatientQueue.setOutpatientQueueStatus(1);
            outpatientQueueMapper.save(outpatientQueue);*/

            return new ResponseResult(200, "操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("挂号异常的异"+e.getMessage());
            return new ResponseResult(206, "挂号异常，请刷新页面重试！");
        }
    }

    /**
     * 补办就诊卡（修改原来的卡号）
     * @param patient
     * @return
     */
    @Override
    public ResponseResult updatePatientInfor(Patient patient) {
        if (patient.getCardId()==null || patient.getCardId().equals("")) {
            return new ResponseResult(203, "新就诊卡卡号不能为空！");
        }
        Patient patientInfo = patientMapper.findByIdCard(patient.getIdCard());
        if (StringUtils.isEmpty(patientInfo)){
            return new ResponseResult(201, "sorry，请检查身份证信息是否有误！");
        }
        patientInfo.setName(patient.getName());
        patientInfo.setSex(patient.getSex());
        patientInfo.setNationality(patient.getNationality());
        patientInfo.setCardId(patient.getCardId());
        patientInfo.setBirthday(patient.getBirthday());
        patientInfo.setAddress(patient.getAddress());
        patientInfo.setTelphone(patient.getTelphone());
        try {
            patientMapper.updatePatientInfo(patientInfo);
            return new ResponseResult(200, "新办就诊卡成功");
        } catch (Exception e) {
            return new ResponseResult(202, "补办就诊卡异常！");
        }
    }


}


//    /**
//     * 补办就诊卡
//     *
//     * @param reqVO
//     * @return
//     */
//    @Override
//    public BaseResponse<String> coverCardId(PatientInforReqVO reqVO) {
//
//        PatientEntity patientInfor = iPatientRepository.findByIdCard(reqVO.getIdCard());
//        if (StringUtils.isEmpty(patientInfor)) {
//            return BaseResponse.error(HisConstants.USER.FAIL);
//        }
//        patientInfor.setCardId(reqVO.getCardId());
//
//        try {
//            iPatientRepository.saveAndFlush(patientInfor);
//            return BaseResponse.success(HisConstants.USER.SUCCESS);
//        } catch (Exception e) {
//            return BaseResponse.error("补办就诊卡异常！");
//        }
//    }

/**
 * 挂号获取医生
 *
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return 保存挂号记录
 * @param reqVO
 * @return 挂号记录查询
 * @param reqVO
 * @return
 */
//    @Override
//    public List<RegisterDoctorRspVO> getAllRegisterDoctor(RegisterTypeReqVO reqVO) {
//
//        List<RegisterDoctorRspVO> registerDoctorRspList = new ArrayList<>();
//
//        List<UserEntity> userList = iUserRepository.findByDepartmentAndDepartmentType(reqVO.getDepartment(), reqVO.getRegisterType());
//
//        if (userList != null && userList.size() > 0) {
//            userList.forEach(user -> {
//                //更新已挂号数
//                if (!DateUtil.getCurrentDateSimpleToString().equals(user.getUpdateTime())) {
//                    user.setNowNum(0);
//                    user.setUpdateTime(DateUtil.getCurrentDateSimpleToString());
//                    iUserRepository.saveAndFlush(user);
//                }
//                RegisterDoctorRspVO registerDoctorRspVO = new RegisterDoctorRspVO();
//                registerDoctorRspVO.setDoctorName(user.getUsername());
//                registerDoctorRspVO.setAllowNum(user.getAllowNum());
//                registerDoctorRspVO.setNowNum(user.getNowNum());
//                registerDoctorRspVO.setWorkDateTime(user.getWorkDateTime());
//                registerDoctorRspVO.setPrice(user.getTreatmentPrice());
//                registerDoctorRspVO.setId(user.getId());
//                registerDoctorRspVO.setWorkAddress(user.getWorkAddress());
//
//                registerDoctorRspList.add(registerDoctorRspVO);
//            });
//
//        }
//
//        return registerDoctorRspList;
//    }

/**
 * 保存挂号记录
 *
 * @param reqVO
 * @return
 */
//    @Override
//    public BaseResponse<String> addRegisterInfor(RegisterInforReqVO reqVO) {
//
//        try {
//
//            UserEntity user = (UserEntity) SecurityUtils.getSubject().getPrincipal();
//            if (StringUtils.isEmpty(user)) {
//                return BaseResponse.error("登录信息已过期！");
//            }
//            Optional<UserEntity> userDoctor = iUserRepository.findById(reqVO.getDoctorId());
//
//            if (!userDoctor.isPresent()) {
//                return BaseResponse.error("未查询到相关医生信息，请稍后重试！");
//            }
//            int allowNum = userDoctor.get().getAllowNum();
//            int nowNum = userDoctor.get().getNowNum();
//            if (nowNum == allowNum) {
//                return BaseResponse.error("该医生已挂号人数已达上限，请刷新页面重新选择！");
//            }
//
//
//            PatientEntity patient = iPatientRepository.findByCardId(reqVO.getCardId());
//
//            //患者当前门诊队列状态是待处理，验证第二次挂的是否为体检号
//            List<RegisterEntity> registerTemp = iRegisterRepository.findAll(new Specification<RegisterEntity>() {
//                @Override
//                public Predicate toPredicate(Root<RegisterEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//                    List<Predicate> filter = new ArrayList<>();
//
//                    filter.add(cb.equal(root.get("patient"), patient));
//                    filter.add(cb.equal(root.get("registerStatus"), 1));
//                    filter.add(cb.equal(root.get("treatmentStatus"), 0));
//                    //当天
//                    String nowDate = DateUtil.getCurrentDateSimpleToString();
//                    filter.add(cb.between(root.get("createDatetime"), nowDate.concat(" 00:00:00"), nowDate.concat(" 23:59:59")));
//
//                    return query.where(filter.toArray(new Predicate[filter.size()])).getRestriction();
//                }
//            });
//            if (registerTemp != null && !registerTemp.isEmpty()) {
//
//                if (registerTemp.size() != 1) {
//                    return BaseResponse.error("挂号记录异常，请联系管理员！");
//                }
//                if (!"12".equals(reqVO.getDepartment())) {
//                    return BaseResponse.error("门诊待处理状态，只允许再挂体检号！");
//                }
//            }
//
//
//            //更新已挂号数量
//            userDoctor.get().setNowNum(nowNum + 1);
//            iUserRepository.saveAndFlush(userDoctor.get());
//
//            //保存挂号记录
//            RegisterEntity register = new RegisterEntity();
//            register.setDepartment(reqVO.getDepartment());
//            register.setDoctor(reqVO.getDoctor());
//            register.setDoctorId(reqVO.getDoctorId());
//            register.setOperatorName(user.getUsername());
//            register.setOperatorEmail(user.getEmail());
//            register.setPatient(patient);
//            register.setPayType(reqVO.getPayType());
//            register.setRegisterType(reqVO.getRegisterType());
//            register.setTreatmentPrice(reqVO.getTreatmentPrice());
//            register.setRegisterStatus(1);
//
//            String registeredNum = "RE" + System.currentTimeMillis() + (int) (Math.random() * 900 + 100);
//            register.setRegisteredNum(registeredNum);
//
//            iRegisterRepository.saveAndFlush(register);
//
//            //将患者加入门诊队列
//            OutpatientQueueEntity outpatientQueue = new OutpatientQueueEntity();
//
//            outpatientQueue.setPatient(patient);
//            outpatientQueue.setRegister(register);
//            outpatientQueue.setUser(userDoctor.get());
//            outpatientQueue.setDescription(patient.getName() + '#' + userDoctor.get().getUsername());
//            outpatientQueue.setOutpatientQueueStatus(HisConstants.QUEUE.NORMAL);
//
//            iOutpatientQueueRepository.saveAndFlush(outpatientQueue);
//
//            return BaseResponse.success(HisConstants.USER.SUCCESS);
//        } catch (Exception e) {
//            logger.error("保存挂号记录异常！", e);
//            return BaseResponse.error("挂号异常，请刷新页面重试！");
//        }
//    }

/**
 * 挂号记录查询
 *
 * @param reqVO
 * @return
 */
//    @Override
//    public PageRspVO<RegisterRecordRspVO> getRegisterRecord(RegisterRecordSearchReqVO reqVO) {
//        Page<RegisterEntity> page = iRegisterRepository.findAll(new Specification<RegisterEntity>() {
//            @Override
//            public Predicate toPredicate(Root<RegisterEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//                List<Predicate> predicateList = new ArrayList<>();
//
//                if (!StringUtils.isEmpty(reqVO.getDepartment())) {
//                    predicateList.add(cb.equal(root.get("department"), reqVO.getDepartment()));
//                }
//                if (!StringUtils.isEmpty(reqVO.getRegisterType())) {
//                    predicateList.add(cb.equal(root.get("registerType"), reqVO.getRegisterType()));
//                }
//                if (!StringUtils.isEmpty(reqVO.getStartTime())) {
//                    predicateList.add(cb.greaterThanOrEqualTo(root.get("createDatetime"), reqVO.getStartTime()));
//                }
//                if (!StringUtils.isEmpty(reqVO.getEndTime())) {
//                    predicateList.add(cb.lessThanOrEqualTo(root.get("createDatetime"), reqVO.getEndTime()));
//                }
//
//                //默认列表
//                if (StringUtils.isEmpty(reqVO.getDepartment()) && StringUtils.isEmpty(reqVO.getRegisterType())
//                        && StringUtils.isEmpty(reqVO.getStartTime()) && StringUtils.isEmpty(reqVO.getEndTime())) {
//                    predicateList.add(cb.greaterThanOrEqualTo(root.get("createDatetime"), now().toString()));
//                }
//
//                query.where(predicateList.toArray(new Predicate[predicateList.size()]));
//                return null;
//            }
//        }, PageRequest.of(reqVO.getPageNumber(), reqVO.getPageSize(), Sort.Direction.DESC, "createDatetime"));
//        if (page == null) {
//            return null;
//        }
//        List<RegisterEntity> registerList = page.getContent();
//        List<RegisterRecordRspVO> registerRecordList = new ArrayList<>();
//        registerList.forEach(register -> {
//            RegisterRecordRspVO registerRecord = new RegisterRecordRspVO();
//            registerRecord.setCardId(register.getPatient().getCardId());
//
//            String departmentName = "";
//            DepartmentEntity department = iDepartmentRepository.findByCode(Integer.parseInt(register.getDepartment()));
//            if (department != null) {
//                departmentName = department.getName();
//            }
//            registerRecord.setDepartment(departmentName);
//
//            registerRecord.setRegisterType(register.getRegisterType());
//            registerRecord.setName(register.getPatient().getName());
//            registerRecord.setDoctor(register.getDoctor());
//            registerRecord.setCreateDateTime(register.getCreateDatetime());
//            registerRecord.setCreatePerson(register.getOperatorName());
//            registerRecord.setCreatePersonEmail(register.getOperatorEmail());
//            registerRecordList.add(registerRecord);
//        });
//        PageRspVO pageRspVO = new PageRspVO();
//        pageRspVO.setTotal(page.getTotalElements());
//        pageRspVO.setRows(registerRecordList);
//        return pageRspVO;
//    }

//    }
